package com.shiyue.cqe.service.impl;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.springframework.beans.factory.InitializingBean;

import com.shiyue.cqe.bind.xml.bean.CQEMapping;
import com.shiyue.cqe.bind.xml.bean.HtmlSelect;
import com.shiyue.cqe.bind.xml.bean.Select;
import com.shiyue.cqe.service.ParseTemplateService;
import com.shiyue.cqe.service.common.TableHelper;

public class InitServiceImpl implements InitializingBean{
	private static final Log log = LogFactory.getLog(InitServiceImpl.class );
	
	private ParseTemplateService parseTemplateService;
	

	public ParseTemplateService getParseTemplateService() {
		return parseTemplateService;
	}


	public void setParseTemplateService(ParseTemplateService parseTemplateService) {
		this.parseTemplateService = parseTemplateService;
	}


	public void afterPropertiesSet() throws Exception {
		parseHtmlSelectXml();
		Serializer serializer = new Persister();
		File file = new File(InitServiceImpl.class.getResource("/").toString().replaceAll("file:", "") + "template");
		File[] files = file.listFiles();
		for(File f : files){
			if(f.isFile()){
				log.info("正在解析项目启动时模板文件：" + f.getName());
				CQEMapping cqeMapping = serializer.read(CQEMapping.class, f);
				parseTemplateService.modifyParseTable(cqeMapping.getTables());
			}
		}
	}
	
	
	private void parseHtmlSelectXml() throws Exception{
		Serializer serializer = new Persister();
		File file = new File(InitServiceImpl.class.getResource("/").toString().replaceAll("file:", "") + "template/select");
		File[] files = file.listFiles();
		for(File f : files){
			if(f.isFile()){
				log.info("正在解析项目启动时htmlSelect文件：" + f.getName());
				HtmlSelect htmlSelect = serializer.read(HtmlSelect.class, f);
				Map<String,Select> selects = new HashMap<String,Select>();
				if(htmlSelect.getSelects() != null){
					for(Select select : htmlSelect.getSelects()){
						selects.put(select.getName(),select);
					}
				}
				TableHelper.setSelects(selects);
			}
		}
	}
}
